﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 * 
 * @author 失足程序员
 * @Blog http://www.cnblogs.com/shizuchengxuyuan/
 * @mail 492794628@qq.com
 * @phone 13882122019
 * 
 */
namespace Net.Sz.Framework.Utils
{
    /// <summary>
    /// 每小时能产生 329496 个 id 100000 ~ 429496，
    /// <para>不保证多程序重复性</para>
    /// <para>启动程序后，重复周期是 一个月,</para>
    /// <para>上一次启动和下一次启动之间重启周期是一小时</para>
    /// <para>PS:</para>
    /// <para>@author 失足程序员</para>
    /// <para>@Blog http://www.cnblogs.com/shizuchengxuyuan/</para>
    /// <para>@mail 492794628@qq.com</para>
    /// <para>@phone 13882122019</para>
    /// </summary>
    public class UIntegerIdUtil
    {

        /// <summary>
        /// 每小时能产生 329496 个 id 100000 ~ 429496，
        /// <para>不保证多程序重复性</para>
        /// <para>启动程序后，重复周期是 一个月,</para>
        /// <para>上一次启动和下一次启动之间重启周期是一小时</para>
        /// </summary>
        public UIntegerIdUtil()
        {

        }

        protected long upTime = 0;
        protected uint MAXHEAD = 1000000;
        protected uint idHead = 0;
        protected uint id = 99999;

        /// <summary>
        /// 每小时能产生 329496 个 id 100000 ~ 429496，
        /// <para>不保证多程序重复性</para>
        /// <para>启动程序后，重复周期是 一个月,</para>
        /// <para>上一次启动和下一次启动之间重启周期是一小时</para>
        /// </summary>
        /// <returns></returns>
        public uint GetId()
        {
            long now = TimeUtil.CurrentTimeMillis() / 3600000;
            uint tmpid = 0;
            /* 这里的锁基本不耗时 */
            lock (this)
            {
                if (now != upTime)
                {
                    upTime = now;
                    /*这一段相对而言，比较耗时*/
                    String tmpyear = DateTime.Now.ToString("ddHH");
                    idHead = Convert.ToUInt32(tmpyear) * MAXHEAD;
                    id = 99999;
                }
                ++id;
                tmpid = id;
            }
            if (429496 < tmpid)
            {
                throw new Exception("超过每分钟创建量 329496");
            }
            return idHead + tmpid;
        }
    }
}
